package com.appsky.drift.activity;

import com.appsky.drift.R;
import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

public class InputIpActivity extends Activity {

	AppSkyApp app;

	Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (AppSkyApp) getApplication();
		intent = new Intent(InputIpActivity.this, DriftActivity.class);
	}

	@Override
	protected void onStart() {
		showDialog(1);
		super.onStart();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			final EditText edit = new EditText(InputIpActivity.this);
			edit.setHint("例如:192.168.1.1");
			return new AlertDialog.Builder(InputIpActivity.this)
					.setIcon(R.drawable.ic_dialog_alert)
					.setTitle("当前为测试模式")
					.setMessage("请输入服务器IP：")
					.setView(edit)
					.setPositiveButton(R.string.ok, new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String str = edit.getText().toString();
							if (isOk(str)) {
								app.setIp(str);
								startActivity(intent);
								finish();
							} else {
								Toast.makeText(InputIpActivity.this,
										"您输入的IP格式有误，请重新输入", Toast.LENGTH_SHORT)
										.show();
								onStart();
							}
						}
					})
					.setNegativeButton(R.string.cancel, new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}).show();
		}
		return super.onCreateDialog(id);
	}

	private boolean isOk(String str) {
		if (Utils.isNullString(str)) {
			return false;
		} else if (isNotIp(str)) {
			return false;
		} else {
			return true;
		}
	}

	private boolean isNotIp(String str) {
		return !isIp(str);
	}

	private boolean isIp(String str) {
		String reg = "[\\d]{1,3}(\\.[\\d]{1,3}){3}";
		return str.matches(reg);
	}
}
